﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;
using Telerik.Web.UI;


public partial class Admin_MembershipProvider_Access_users_by_role : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    private void Page_Init()
    {
        UserRoles.DataSource = System.Web.Security.Roles.GetAllRoles();
        UserRoles.DataBind();
    }

    private void Page_PreRender()
    {
        /*
         * Dan Clem, 3/7/2007 and 4/27/2007.
         * The logic here is necessitated by the limitations of the built-in object model.
         * The Membership class does not provide a method to get users by role.
         * The Roles class DOES provide a GetUsersInRole method, but it returns an array of UserName strings
         * rather than a proper collection of MembershipUser objects.
         * 
         * This is my workaround.
         * 
         * Note to self: the two-collection approach is necessitated because you can't remove items from a collection
         * while iterating through it: "Collection was modified; enumeration operation may not execute."
         */

        MembershipUserCollection allUsers = Membership.GetAllUsers();
        MembershipUserCollection filteredUsers = new MembershipUserCollection();

        if (UserRoles.SelectedIndex > 0)
        {
            string[] usersInRole = System.Web.Security.Roles.GetUsersInRole(UserRoles.SelectedValue);
            foreach (MembershipUser user in allUsers)
            {
                foreach (string userInRole in usersInRole)
                {
                    if (userInRole == user.UserName)
                    {
                        filteredUsers.Add(user);
                        break; // Breaks out of the inner foreach loop to avoid unneeded checking.
                    }
                }
            }
        }
        else
        {
            filteredUsers = allUsers;
        }
        Users1.DataSource = filteredUsers;
        Users1.DataBind();
    }

    protected void Users1_NeedDataSource(object source, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
    {

    }

    protected void Users1_DeleteCommand(object source, Telerik.Web.UI.GridCommandEventArgs e)
    {
        string UserName = (e.Item as GridDataItem).OwnerTableView.DataKeyValues[e.Item.ItemIndex]["UserName"].ToString();
        Membership.DeleteUser(UserName, true);
        this.Users1.MasterTableView.Rebind();
    }
}
